layui.use(['jquery','layer','table','form','upload'],function(){
    var $=layui.jquery;
    var layer=layui.layer;
    var table=layui.table;
    var form=layui.form;
    var upload=layui.upload;
    var createTime = "";
    var updateDate = "";
    judge();
    demoTable();

    function judge(){
        var user = localStorage.getItem('user');
        user = JSON.parse(user);
        var userId = user.data.userId;
        $.ajax({
            url: '/product/judgePower',
            type: 'post',
            dataType: 'json',
            data: {'id':userId},
            success: function (data) {
                if(data.data.contains(1)){
                    demoZtree();
                }else{
                    demoZtreeOther();
                }
            }
        })
    }
    $.ajax({
        url: '/SyStatistical/getSyProductCategroys',
        dataType: 'json',
        type: 'post',
        success: function (data) {
            var syProductCategroys = data.data;
            for (var i = 0; i < syProductCategroys.length; i++) {
                $('#title').append('<option value="' + syProductCategroys[i].title + '" >' + syProductCategroys[i].title + '</option>')

            }
            form.render('select');
        }
    });

    refresh=function refresh(){
        location.reload();
    }

    function demoZtree(){
        var setting = {
            data: {
                simpleData: {
                    enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                    idKey: "categroyId",  //节点数据中保存唯一标识的属性名称
                    pIdKey: "parentId",    //节点数据中保存其父节点唯一标识的属性名称
                    rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
                },
                key: {
                    name: "title"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
                }
            },
            view: {
                dblClickExpand: false
            },
            check: {
                enable:false,  //true 、 false 分别表示 显示 、不显示 复选框或单选框
                nocheckInherit:true  //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
            },
            callback: {
               onRightClick: OnRightClick,
                beforeRename: beforeRename,
                onClick:zTreeOnClick
            }
        };

        function OnRightClick(event, treeId, treeNode) {
            if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
                zTree.cancelSelectedNode();
                showRMenu("root", event.clientX, event.clientY);
            } else if (treeNode && !treeNode.noR) {
                zTree.selectNode(treeNode);
                showRMenu("node", event.clientX, event.clientY);
            }
        }
        //修改前判断
        function beforeRename(treeId, treeNode, newName) {
            if (newName.length == 0) {
                alert("节点名称不能为空.");
                var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                setTimeout(function(){zTree.editName(treeNode)}, 10);
                return false;
            }
            return true;
        }
        function showRMenu(type, x, y) {
            $("#rMenu ul").show();
            if (type=="root") {
                $("#m_del").hide();
            } else {
                $("#m_del").show();
            }

            y += document.body.scrollTop;
            x += document.body.scrollLeft;
            rMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});

            $("body").bind("mousedown", onBodyMouseDown);
        }

        function hideRMenu() {
            if (rMenu) rMenu.css({"visibility": "hidden"});
            $("body").unbind("mousedown", onBodyMouseDown);
        }
        function onBodyMouseDown(event){
            if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length>0)) {
                rMenu.css({"visibility" : "hidden"});
            }
        }
        //添加树节点
        addTreeNode = function addTreeNode() {
            hideRMenu();
            var nodes = zTree.getSelectedNodes();
            var parentId = nodes[0].categroyId;
            layer.open({
                type:1,
                title:"添加节点",
                area:['400px','220px'],
                shade:0.4,
                offset:['250px','650px'],
                content:"<form class='layui-form'><div class='layui-form-item' style='margin: 20px;'>"+
                    "<label class='layui-input-label'>添加分类：</label>"
                    +"<div class='layui-input-block'>"
                    +"<input type='text' name='title' style='width:220px;height:30px;'id='addNode' lay-verify='required' placeholder='商品分类'>"
                    +"</div>"+"</div></form>",
                btn:['添加','取消'],
                yes:function () {
                    var title = $("#addNode").val();
                    if(title.length != 0){
                        $.ajax({
                            url: '/product/addProductTree',
                            type: 'post',
                            dataType: 'json',
                            data: {'parentId':parentId,'title':title},
                            success: function (data) {
                                if(data.data){
                                    location.reload();
                                }
                            }
                        })
                    }else {
                        layer.msg("分类名不能为空");
                    }
                }
            })
        }
        //删除树节点
        removeTreeNode = function removeTreeNode() {
            hideRMenu();
            var nodes = zTree.getSelectedNodes();
            var categroyId = nodes[0].categroyId;
            if (nodes && nodes.length>0) {
                $.ajax({
                    url: '/product/deleteProductTree',
                    type: 'post',
                    dataType: 'json',
                    data: {'categroyId':categroyId},
                    beforeSend: function () {
                        if (nodes[0].children && nodes[0].children.length > 0){
                            return confirm("要删除的节点是父节点，如果删除将连同子节点一起删掉。请确认？")
                        }else {
                            return confirm("确认删除？")
                        }
                    },
                    success: function (data) {
                        if(data.data){
                            zTree.removeNode(nodes[0]);
                            layer.msg("删除成功")
                        }
                    }
                })
            }
        }

        //修改树节点
        edit = function edit() {
            hideRMenu();
            var nodes = zTree.getSelectedNodes();
            var categroyId = nodes[0].categroyId;
            layer.open({
                type:1,
                title:"修改节点",
                area:['400px','220px'],
                shade:0.4,
                offset:['250px','650px'],
                content:"<form class='layui-form'><div class='layui-form-item' style='margin: 20px;'>"+
                    "<label class='layui-input-label'>修改分类：</label>"
                    +"<div class='layui-input-block'>"
                    +"<input type='text' name='title' style='width:220px;height:30px;'id='updateNode' lay-verify='required' placeholder='商品分类'>"
                    +"</div>"+"</div></form>",
                btn:['修改','取消'],
                yes:function () {
                    var title = $("#updateNode").val();
                    if(title.length != 0){
                        $.ajax({
                            url: '/product/updateProductTree',
                            type: 'post',
                            dataType: 'json',
                            data: {'title':title,'categroyId':categroyId},
                            success: function (data) {
                                if(data.data){
                                    location.reload();
                                }
                            }
                        })
                    }else {
                        layer.msg("分类名不能为空");
                    }
                }
            })
        }
        //点击节点，展示对应类别下商品信息
        function zTreeOnClick() {
            var nodes = zTree.getSelectedNodes();
            var node = nodes[0];
            categroyId = node.categroyId;
            if(!node.isParent){
                $.ajax({
                    url: '/product/getCheckedProduct',
                    type: 'post',
                    dataType: 'json',
                    data: {'categroyId':categroyId},
                    success: function (data) {
                        demoTable(data.data);
                    }
                })
            }else{
                layer.msg("请选择最小分类类别");
            }
        }
        //加载树
        var zTree, rMenu;
        $(document).ready(function(){
            $.ajax({
                url: '/product/getProductTree',
                type: 'post',
                dataType: 'json',
                success: function (data) {
                    zTree = $.fn.zTree.init($("#treeDemo"), setting, data.data);//初始化树
                    zTree.expandAll(true);    //true 节点全部展开、false节点收缩
                }
            })
            rMenu = $("#rMenu");
        });
    }
    function demoZtreeOther(){
        var setting = {
            data: {
                simpleData: {
                    enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                    idKey: "categroyId",  //节点数据中保存唯一标识的属性名称
                    pIdKey: "parentId",    //节点数据中保存其父节点唯一标识的属性名称
                    rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
                },
                key: {
                    name: "title"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
                }
            },
            view: {
                dblClickExpand: false
            },
            check: {
                enable:true,  //true 、 false 分别表示 显示 、不显示 复选框或单选框
                nocheckInherit:true  //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
            },
            callback: {
                onClick:zTreeOnClick
            }
        };
        //点击节点，展示对应类别下商品信息
        function zTreeOnClick() {
            var nodes = zTree.getSelectedNodes();
            var node = nodes[0];
            categroyId = node.categroyId;
            if(!node.isParent){
                $.ajax({
                    url: '/product/getCheckedProduct',
                    type: 'post',
                    dataType: 'json',
                    data: {'categroyId':categroyId},
                    success: function (data) {
                        demoTable(data.data);
                    }
                })
            }else{
                layer.msg("请选择最小分类类别");
            }
        }
        //加载树
        var zTree, rMenu;
        $(document).ready(function(){
            $.ajax({
                url: '/product/getProductTree',
                type: 'post',
                dataType: 'json',
                success: function (data) {
                    zTree = $.fn.zTree.init($("#treeDemo"), setting, data.data);//初始化树
                    zTree.expandAll(true);    //true 节点全部展开、false节点收缩
                }
            })
        });
    }

    retrieval = function retrieval(){
        layer.open({
            type : 2,
            title : "高级检索",
            area : [ '900px', '580px' ],
            shade : 0,
            offset: 'auto',
            btn:['确定','取消'],
            content :"product-sample.html",
            yes: function(index, layero){
                var child = layero.find('iframe').contents();
                var productCode=child.find("input[name=productCode]").val();
                var productSate=child.find("#productSate option:selected").val();
                var currentpriceProduct=child.find("input[name=currentpriceProduct]").val();
                var title=child.find("#title option:selected").text();
                var productName=child.find("input[name=productName]").val();
                var productLabel=child.find("input[name=productLabel]").val();
                var param = {
                    'productCode':productCode,
                    'productSate':productSate,
                    'currentpriceProduct':currentpriceProduct,
                    'title':title,
                    'productName':productName,
                    'productLabel':productLabel,
                }
                $.ajax({
                    url:"/product/getProductRetrieval",
                    data:param,
                    type:"post",
                    dataType:"json",
                    success:function (data) {
                        demoTable(data.data);
                        layer.close(layer.index);
                    }
                })
            }
        })
    }

    getTable('','','','');

    function getTable(productName,title,productSate,productLabel){
        $.ajax({
            url:"/product/getProductSearch",
            type:"post",
            dataType:"json",
            data:{'productName':productName,'title':title,'productSate':productSate,'productLabel':productLabel},
            success:function (data) {
                demoTable(data.data);
            }
        })
    }

    search = function search(){
        var productName=$("input[name=productName]").val();
        var title=$("#title option:selected").text();
        var productSate;
        if($("#productSate option:selected").text()=="上架"){
            productSate=$("#productSate option:selected").val();
        }else if($("#productSate option:selected").text()=="下架"){
            productSate=$("#productSate option:selected").val();
        }else if($("#productSate option:selected").text()=="已删除"){
            productSate=$("#productSate option:selected").val();
        }
        var productLabel=$("input[name=productLabel]").val();
        getTable(productName,title,productSate,productLabel);
    }

    /*表格*/
    function demoTable(data){
        var tableRender = table.render({
            elem:'#demoTable',
            title:"委托书",
            data:data,
            toolbar:'#button_ids',
            limit:10,
            width:1320,
            page:{
                layout:['count','prev','page','next','limit','skip','refresh'],
                limits:[10,20,30],
                first:"首页",
                last:"尾页",
            },
            cols:[[
                {type:'checkbox'},
                {field:"productCode",title:"商品编号",align:'center',width:130},
                {field:"mainImage",title:"商品图片",align:'center',width:170,templet:function(data){
                        return '<img src="'+data.mainImage+'"';
                    }},
                {field:"productName",title:"商品名称",align:'center',width:160},
                {field:"currentpriceProduct",title:"商品价格",align:'center',width:125,templet:function(data){
                        return '<p>￥'+data.currentpriceProduct+'</p>';
                    }},
                {field:"productSate",title:"上架/下架",align:'center',width:125,templet:function(data){
                    if(data.productSate==1){
                        return '<input type=\"checkbox\" value="'+data.productCode+'" lay-skin=\"switch\" lay-text=\"上架|下架"\ checked lay-filter="switchTest">';
                    }else if(data.productSate==2){
                        return '<input type=\"checkbox\" value="'+data.productCode+'" lay-skin=\"switch\" lay-text=\"上架|下架" lay-filter="switchTest"\>';
                    }else if(data.productSate==3){
                        return '<p>已删除</p>';
                    }
                }},
                {field:"title",title:"商品分类",align:'center',width:125},
                {field:"productLabel",title:"商品标签",align:'center',width:125},
                {field:"result",title:"审核状态",align:'center',width:125,templet:function(data){
                        var result;
                        if(data.result==2){
                            result="待审核";
                        }else if(data.result==1){
                            result="审核通过";
                        }else if(data.result==3){
                            result="审核驳回";
                        }
                        return '<p>'+result+'</p><p style="color: #00B83F" onclick="productExamine('+data.productId+')">审核详情</p>';
                    }},
                {field:'',title:"操作",align:'center',width:175,toolbar:'#button_caozuo'}
            ]]
        })

        productExamine=function productExamine(productId){
            layer.open({
                type:2,
                title:"商品审核详情",
                area:['800px',"500px"],
                btn:["确定","取消"],
                offset:'auto',
                content:"product-examine.html",
                success:function(layero,index){
                    var child = layero.find('iframe').contents();
                    child.find("input[name=productId]").val(productId);
                }
            })
        }

        table.on('tool(demoTable)',function (obj) {
            localStorage.setItem("updateDate",JSON.stringify(obj.data));
            var event = obj.event;
            if (event == "selectTable"){
                var param = {
                    'logType':1,
                    "type":5,
                    "userId":obj.data.createId,
                    'createDate':getTime(),
                    'remark':'查看反馈统计',
                }
                $.ajax({
                    url:"/JsLog/addProductJsLog",
                    data:param,
                    type:'post',
                    dataType:'text',
                    success:function (data) {
                    }
                });
                layer.open({
                    type:2,
                    title:"查看",
                    area:["95%","100%"],
                    scrollbar: false,
                    offset:'auto',
                    btn:["确定","取消"],
                    content:"product-tool-select.html",
                    success:function(layero,index){
                        var child = layero.find('iframe').contents();
                        $.ajax({
                            url:"/product/getUserCollection",
                            data:{"productCode":obj.data.productCode},
                            type:'post',
                            dataType:'json',
                            success:function (data) {
                                if(data.data==null||data.data==0){
                                    child.find("#Collection").text(0);
                                }else{
                                    child.find("#Collection").text(data.data);
                                }
                            }
                        })
                        child.find("#productName").text(obj.data.productName);
                        child.find("#createDate").text(obj.data.createDate);
                        child.find("#createName").text(obj.data.createName);
                        child.find("#keyWords").text(obj.data.searchKeywords);
                        child.find("#currentpriceProduct").text(obj.data.currentpriceProduct);
                        child.find("#title").text(obj.data.title);
                        if(obj.data.productSate==1){
                            child.find("#productSate").text("上架");
                        }else if(obj.data.productSate==2){
                            child.find("#productSate").text("下架");
                        }
                        child.find("#productDescription").text(obj.data.productDescription);
                        child.find("#mainImage").attr("src",obj.data.mainImage);
                        if(obj.data.hits==0||obj.data.hits==null){
                            child.find("#hits").text(0);
                        }else{
                            child.find("#hits").text(obj.data.hits);
                        }
                    },
                    end:function (layero, index) {
                        layer.close(index);
                    }
                });
            }else if (event == "updateTable") {
                var param = {
                    'logType':1,
                    "type":4,
                    "userId":obj.data.createId,
                    'createDate':getTime(),
                    'remark':'编辑反馈统计',
                }
                $.ajax({
                    url:"/JsLog/addProductJsLog",
                    data:param,
                    type:'post',
                    dataType:'text',
                    success:function (data) {
                    }
                });
                layer.open({
                    type:2,
                    title:"修改",
                    area:["800px","600px"],
                    btn:["确定","取消"],
                    offset: 'auto',
                    content:"product-list-tool-update.html",
                    yes:function( index,layero){
                        var childUpdate = layero.find('iframe').contents();

                        getTime();

                        var xianjia=childUpdate.find("input[name=currentpriceProduct]").val();
                        var bianhao=childUpdate.find("input[name=productCode]").val();
                        var shangpin=childUpdate.find("input[name=productName]").val();

                        var param = {
                            'productCode':childUpdate.find("input[name=productCode]").val(),
                            'productName':childUpdate.find("input[name=productName]").val(),
                            'currentpriceProduct':childUpdate.find("input[name=currentpriceProduct]").val(),
                            'productSate':childUpdate.find("#productSate").val(),
                            'title':childUpdate.find("input[name=title]").val(),
                            'productDescription':childUpdate.find("#productDescription").val(),
                            'updateDate':updateDate,
                            'updateId':JSON.parse(localStorage.getItem('user')).data.userId
                        }
                        $.ajax({
                            url:"/product/updateByProductCodeProduct",
                            data:param,
                            type:'post',
                            dataType:'json',
                            success:function (data) {
                                if(obj.data.currentpriceProduct!=xianjia){
                                    getTime();
                                    var params={
                                        'dictLabel':shangpin,
                                        'dictValue':bianhao,
                                        'dictType':12,
                                        'cssClass':obj.data.currentpriceProduct,
                                        'listClass':xianjia,
                                        'createTime':createTime
                                    }
                                    $.ajax({
                                        url:"/SyDictData/addProductPrice",
                                        data:params,
                                        type:'post',
                                        dataType:'json',
                                        success:function (data) {
                                        }
                                    })
                                }
                                getTable("","","","");
                            }
                        })
                        layer.close(index);
                    },
                    btn2:function(index,layero){
                        layer.close(index);
                    },
                    end:function () {
                        getTable("","","","");
                    }
                });
            }else if (event == "journalTable") {
                layer.open({
                    type:2,
                    title:"商品价格操作日志",
                    area:["95%","100%"],
                    scrollbar: false,
                    offset:'auto',
                    btn:["确定","取消"],
                    content:"product-log.html",
                })
                var param = {
                    'logType':1,
                    "type":1,
                    "userId":obj.data.createId,
                    'createDate':getTime(),
                    'remark':'日志反馈统计',
                }
                $.ajax({
                    url:"/JsLog/addProductJsLog",
                    data:param,
                    type:'post',
                    dataType:'text',
                    success:function (data) {
                    }
                });
            }else if(event == "deleteTable") {
                var productCode = obj.data.productCode;
                var productData = obj.data;
                layer.confirm('确认要删除吗?', {icon: 3, title:'提示'}, function(index){
                    var param = {
                        'logType':1,
                        "type":3,
                        "userId":obj.data.createId,
                        'createDate':getTime(),
                        'remark':'删除反馈统计',
                    }
                    $.ajax({
                        url:"/JsLog/addProductJsLog",
                        data:param,
                        type:'post',
                        dataType:'text',
                        success:function (data) {
                        }
                    });
                    $.ajax({
                        url:"/product/deleteByProductCodeProduct",
                        data:{'productCode':productCode},
                        type:'post',
                        dataType:'json',
                        success:function (data) {
                            getTable("","","","");
                        }
                    })
                    $.ajax({
                        url:"/product/deleteProductRecord",
                        data:{'courseId':obj.data.productId},
                        type:'post',
                        dataType:'json',
                        success:function (data) {
                            layer.msg("删除成功");
                        }
                    })
                    layer.close(index);
                });
            }else {
                console.log("为什么会点到我，好好反省反省！！！");
            }
        })
    }

    form.on('switch(switchTest)', function(data){
        if(data.elem.checked==true){
            $.ajax({
                url:"/product/updateProductState",
                type:"post",
                dataType:"json",
                data:{'productSate':1,'productCode':data.value},
                success:function (data) {
                    getTable("","","","","");
                    layer.msg("修改成功");
                }
            })
        }else{
            $.ajax({
                url:"/product/updateProductState",
                type:"post",
                dataType:"json",
                data:{'productSate':2,'productCode':data.value},
                success:function (data) {
                    getTable("","","","","");
                    layer.msg("修改成功");
                }
            })
        }
    })


    addButton = function addButton() {
        parent.$('#quickEntry').val("添加商品");
        parent.quickEntry();
    }

    //返回按钮
    $('#goBack').click(function () {
        var title = $('#titleName').text();
        var iframe = parent.$('.iframe');
        $.each(iframe,function (i,item) {
            if(title == $(item).attr('_href')){
                parent.$('#beforeHref').val($(item).attr('_href'));
                parent.beforeHref();
                return;
            }
        });
    });

    leading=function leading(){
        layer.open({
            type:2,
            title:"上传文件",
            area:["400px","300px"],
            btn:["确定","取消"],
            offset: 'auto',
            content:"ExcelUpload.html",
        })
    }

    //现在时间
    function getTime(){
        var date=new Date();
        var year=date.getFullYear();
        var month=date.getMonth()+1;
        var day=date.getDate();
        var hour=date.getHours();
        var minute=date.getMinutes();
        var second=date.getSeconds();
        var dateStr = year+"-"+zeroFilling(month)+"-"+zeroFilling(day)+" "+zeroFilling(hour)+":"+zeroFilling(minute)+":"+zeroFilling(second);
        updateDate = dateStr;
        createTime = dateStr;
        return dateStr;
    }
    function zeroFilling(data){
        if(data<10){
            data="0"+data;
        }
        return data;
    }

    //点击后父页面右键关闭选项卡元素隐藏
    $(document).click(function () {
        parent.$('.tab').hide();
    });
})